<template>
  <div class="school-manage" v-loading="loading">
    <div class="school-manage-header" v-if="level < 4">
      <div class="header-content">
        <div class="header-left">
          <select-region v-model:areaId="areaId"></select-region>
          <!-- <el-select v-model="platform" value-key="id" placeholder="使用平台" size="medium">
            <el-option
              v-for="item in platformList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select> -->
          <!-- <el-select v-model="useType" value-key="id" placeholder="使用类型" size="medium">
            <el-option
              v-for="item in useTypeList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select> -->
          <div class="search-input-wrapper">
            <el-input
              v-model="keyword"
              placeholder="请输入学校名称"
              id="school-name-input"
              @keypress.enter="changeInput"
              @input="handleSearchInput"
              prefix-icon="el-icon-search"
              size="default"
              clearable
            ></el-input>
            <el-button type="primary" icon="el-icon-search" size="default" @click="changeInput" class="search-button">搜索</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="school-manage-body">
      <div class="table-card">
        <div class="table-header">
          <div class="table-title">
            <i class="el-icon-school"></i>
            <span>学校管理</span>
          </div>
          <div class="table-actions">
            <div class="school-count">
              <i class="el-icon-school"></i>
              <span>学校: <strong>{{ schoolCount }}</strong> 所</span>
            </div>
            <!-- <el-button type="warning" icon="el-icon-star-on" size="medium" @click="openMemberShip">开通会员</el-button> -->
            <!-- <el-button type="info" icon="el-icon-download" size="medium" @click="exportData">导出数据</el-button> -->
            <ButtonPermission code="school:add" mode="disable">
              <template #default="{ disabled }">
                <el-button 
                  type="success" 
                  icon="el-icon-plus" 
                  size="default"
                  :disabled="disabled"
                  @click="!disabled && openAddSchool()"
                >添加学校</el-button>
              </template>
            </ButtonPermission>
          </div>
        </div>
        <div class="current-school-info" v-if="currentSchoolId">
          <div class="current-school-tag">
            <i class="el-icon-check"></i>
            <span>当前选中：{{ currentSchoolName }}</span>
            <span class="school-id">(ID: {{ currentSchoolId }})</span>
          </div>
          <el-button type="text" size="small" @click="clearCurrentSchool">
            <i class="el-icon-close"></i> 取消选中
          </el-button>
        </div>
        <div class="table-wrapper">
          <el-table 
            :data="schools" 
            stripe 
            border 
            highlight-current-row
            :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266', fontWeight: 'bold'}"
            :row-class-name="getRowClassName"
            class="responsive-table"
          >
            <!-- <el-table-column type="selection"></el-table-column> -->
            <el-table-column
              label="学校ID"
              prop="F_id"
              align="center"
              width="100"
            ></el-table-column>
            <el-table-column 
              label="学校名称" 
              prop="F_name" 
              align="center"
              min-width="180"
            >
              <template #default="scope">
                <div class="school-name-cell" @click="editSchoolName(scope.row)">
                  <span v-if="!scope.row.isEditing">{{ scope.row.F_name }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.editingName"
                    size="small"
                    @blur="saveSchoolName(scope.row)"
                    @keyup.enter="saveSchoolName(scope.row)"
                    ref="schoolNameInput"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="使用类型"
              prop="F_use_type_name"
              align="center"
              width="100"
            ></el-table-column>
            <el-table-column 
              label="地区" 
              prop="F_location" 
              align="center"
              min-width="180"
            ></el-table-column>
            <el-table-column
              label="创建时间"
              prop="F_create_datetime"
              align="center"
              width="180"
            ></el-table-column>
            <el-table-column
              label="管理员姓名"
              prop="F_admin_name"
              align="center"
              width="150"
            ></el-table-column>
            <el-table-column
              label="管理员账号"
              prop="F_admin_account"
              align="center"
              width="180"
            ></el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <!-- <el-button 
                  type="text" 
                  size="small" 
                  @click="selectSchool(scope.row)" 
                  class="action-button"
                  :disabled="currentSchoolId === scope.row.F_id"
                >
                  <i class="el-icon-view"></i> {{ currentSchoolId === scope.row.F_id ? '已选中' : '查看' }}
                </el-button> -->
                <!-- <el-button type="text" size="small" @click="exportId(scope.row)" class="action-button">
                  <i class="el-icon-download"></i> 导出学生ID
                </el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="table-pagination">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="pageSize"
            :total="schoolCount"
            @current-change="changePage"
            @size-change="handleSizeChange"
            v-model:current-page="page"
          ></el-pagination>
        </div>
      </div>
    </div>
    <open-member-ship v-model:visible="showOpenMemberShip"></open-member-ship>
    <add-school 
      v-model:visible="showAddSchool"
      @success="handleAddSuccess">
    </add-school>
  </div>
</template>

<script>
import { downloadExcelBlob } from '@/utils/utils';
import SelectRegion from '@/components/common/selectRegion.vue';
import OpenMemberShip from '@/components/schoolmanage/openMemberShip.vue';
import AddSchool from '@/components/schoolmanage/AddSchool.vue';
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
  name: 'SchoolManage',
  data() {
    return {
      level: 1,
      schoolIds: [],
      platformList: [],
      useTypeList: [],
      platform: {},
      useType: {},
      areaId: 0,
      keyword: '',
      getSchoolMethod: null,
      schools: [],
      schoolCount: 0,
      page: 1,
      pageSize: 20,
      multipleSelection: [],
      loading: false,
      showOpenMemberShip: false,
      showAddSchool: false,
      searchTimer: null, // 新增防抖计时器
    };
  },

  components: {
    SelectRegion,
    OpenMemberShip,
    AddSchool,
  },

  async mounted() {
    this.platformList = this.$maps.platfromList;
    this.useTypeList = this.$maps.useTypeList;
    this.getUserInfo();
    this.getSchoolMethod = this.getSchools;
    // if (this.level >= 4) this.getSchoolMethod = this.getSchoolsByIds;
    // else this.getSchoolMethod = this.getSchools;
    this.getSchoolMethod();
  },
  activated() {
    if (this.level >= 4) {
      if (this.school_list.length === 1) {
        this.selectSchool(this.school_list[0]);
      }
    } else {
      this.getSchoolMethod();
    }
  },
  watch: {
    areaId() {
      this.page = 1;
      this.getSchoolMethod();
    },
    platfrom() {
      console.log('platyfrom:', this.platform);
    },
    useType() {
      this.page = 1;
      this.getSchoolMethod();
    },
  },
  computed: {
    ...mapState('user', ['userInfo']),
    ...mapGetters('user', ['isSuperAdmin']),
    ...mapState('school', ['currentSchoolId', 'schoolInfo', 'schoolList']),
    ...mapGetters('school', ['currentSchool']),
    
    currentSchoolName() {
      if (this.currentSchoolId && this.schools.length > 0) {
        const school = this.schools.find(s => s.F_id === this.currentSchoolId);
        if (school) {
          return school.F_name;
        }
      }
      
      if (this.schoolInfo && this.schoolInfo.F_name) {
        return this.schoolInfo.F_name;
      }
      
      return '未知学校';
    }
  },

  methods: {
    ...mapActions('school', ['SET_CURRENT_SCHOOL', 'GET_SCHOOL_DETAIL', 'GET_SCHOOL_OPTIONS']),
    
    getRowClassName({ row }) {
      return this.currentSchoolId === row.F_id ? 'selected-school-row' : '';
    },
    
    async selectSchool(school) {
      if (this.currentSchoolId === school.F_id) {
        return;
      }
      
      this.loading = true;
      try {
        await this.SET_CURRENT_SCHOOL(school.F_id);
        
        await this.GET_SCHOOL_DETAIL({ school_id: school.F_id });
        await this.GET_SCHOOL_OPTIONS({ school_id: school.F_id });
        
        this.$message({
          type: 'success',
          message: `已切换到学校：${school.F_name}`
        });
      } catch (error) {
        console.error('选择学校失败:', error);
        this.$message.error('切换学校失败，请重试');
      } finally {
        this.loading = false;
      }
    },
    
    clearCurrentSchool() {
      this.SET_CURRENT_SCHOOL('');
    },
    
    getUserInfo() {
      if (this.isSuperAdmin) return;
      const {
        permission: { level, school_list },
      } = this.userInfo;
      this.level = level;
      if (this.level >= 4) {
        this.school_list = school_list;
        this.schoolIds = school_list.map((e) => e.F_id);
        if (school_list.length === 1) {
          this.selectSchool(school_list[0]);
        }
      }
    },
    changeInput() {
      this.page = 1;
      this.getSchoolMethod();
    },
    handleSearchInput() {
      // 使用防抖，避免频繁请求
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      this.searchTimer = setTimeout(() => {
        this.page = 1;
        this.getSchoolMethod();
      }, 500);
    },
    async getSchoolsByIds() {
      this.loading = true;
      const res = await this.$api.getSchoolsByIds({
        F_school_ids: this.schoolIds.join(','),
        // F_school_ids: "193762,132386",
      });
      res.F_schools = res.F_school;
      this.loading = false;
      this.handleSchoolResult(res);
    },
    async getSchools() {
      this.loading = true;
      const res = await this.$api.getSChoolsByAdmin({
        F_page: this.page,
        F_limit: this.pageSize,
        F_area_id: this.areaId,
        F_school_type: this.useType.id,
        F_search_name: this.keyword,
      });
      this.loading = false;
      this.handleSchoolResult(res);
    },
    handleSchoolResult(res) {
      this.schools = res.F_schools || [];
      this.schoolCount = res.F_total;
      this.schools.forEach((school) => {
        const { F_prov_name, F_city_name, F_district_name } = school.F_loc;
        const { F_name, F_account } = school.F_admin;
        school.F_location = F_prov_name + F_city_name + F_district_name;
        school.F_admin_name = F_name;
        school.F_admin_account = F_account;
        school.F_use_type_name = this.useTypeList.find(
          (e) => e.id === school.F_use_type
        ).name;
      });
      // console.log(this.schools);
    },
    handleSelectionChange(val) {
      console.log('this.selectionList:', val);
      this.multipleSelection = val;
    },
    changePage(val) {
      this.page = val;
      this.getSchoolMethod();
    },
    handleSizeChange(val) {
      this.page = 1;
      this.pageSize = val;
      this.getSchoolMethod();
    },
    openMemberShip() {
      this.$toast('功能调整中, 尚未开放');
      console.log('openMemberShip');
      // if (this.multipleSelection.length === 0)
      //   this.$toast("请至少勾选一个学校");
      // else this.showOpenMemberShip = true;
    },
    exportData() {
      this.$toast('功能调整中, 尚未开放');
      console.log('exportData');
    },
    view(item) {
      this.$router.push({
        path: `/homepage/schoolManage/${item.F_id}`,
      });
    },
    async exportId(item) {
      const res = await this.$api.exportStudentId({
        school_id: item.F_id,
      });
      downloadExcelBlob(res, `${item.F_name}学生ID`);
    },
    openAddSchool() {
      this.showAddSchool = true;
    },
    handleAddSuccess() {
      this.getSchoolMethod();
    },
    editSchoolName(row) {
      // 如果当前用户没有权限，则不执行编辑
      if (!this.isSuperAdmin && this.level > 2) {
        return;
      }
      // Vue 3 中不再需要 $set，直接赋值即可
      row.isEditing = true;
      row.editingName = row.F_name;
      this.$nextTick(() => {
        if (this.$refs.schoolNameInput) {
          this.$refs.schoolNameInput.focus();
        }
      });
    },
    async saveSchoolName(row) {
      if (!row.isEditing) return;
      
      const newName = row.editingName.trim();
      if (!newName) {
        this.$message.warning('学校名称不能为空');
        return;
      }
      console.log(newName)
      
      if (newName === row.F_name) {
        row.isEditing = false;
        return;
      }
      
      try {
        this.loading = true;
        const res = await this.$api.updateSchoolName({
          F_school_id: row.F_id,
          F_school_name: newName
        });
        
        if (res.F_responseNo === 10000) {
          row.F_name = newName;
          this.$message.success('学校名称修改成功');
        } else {
          this.$message.error(res.F_responseMsg || '修改失败');
        }
      } catch (error) {
        console.error('修改学校名称失败:', error);
        this.$message.error('修改失败，请重试');
      } finally {
        this.loading = false;
        row.isEditing = false;
      }
    },
  },
  beforeUnmount() {
    // 清理搜索计时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },
};
</script>

<style lang="less" scoped>
.school-manage {
  box-sizing: border-box;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding: 16px;
}

.school-manage-header {
  margin-bottom: 16px;
  
  .header-content {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    
    @media (max-width: 1200px) {
      flex-direction: column;
      align-items: flex-start;
    }
  }
  
  .header-left {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
    width: 100%;
    
    @media (max-width: 768px) {
      flex-direction: column;
      align-items: flex-start;
    }
    
    .search-input-wrapper {
      display: flex;
      align-items: center;
      
      .el-input {
        width: 250px;
      }
      
      .search-button {
        margin-left: 8px;
      }
    }
  }
}

.school-manage-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  .table-card {
    flex: 1;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 16px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .current-school-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding: 8px 16px;
      background-color: #ecf8f6;
      border-left: 3px solid #40DBBC;
      border-radius: 4px;
      
      .current-school-tag {
        display: flex;
        align-items: center;
        color: #303133;
        
        i {
          margin-right: 8px;
          color: #40DBBC;
          font-size: 16px;
        }
        
        .school-id {
          margin-left: 8px;
          font-size: 12px;
          color: #909399;
        }
      }
    }
    
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      .table-title {
        font-size: 18px;
        font-weight: 500;
        color: #303133;
        display: flex;
        align-items: center;
        
        i {
          margin-right: 8px;
          font-size: 20px;
          color: #40DBBC;
        }
      }
      
      .table-actions {
        display: flex;
        align-items: center;
        gap: 16px;
        
        .school-count {
          padding: 8px 16px;
          border-radius: 4px;
          background-color: #f0f7ff;
          color: #606266;
          font-size: 14px;
          display: flex;
          align-items: center;
          
          i {
            margin-right: 6px;
            color: #409EFF;
            font-size: 18px;
          }
          
          strong {
            color: #409EFF;
            margin: 0 4px;
            font-size: 16px;
          }
        }
      }
    }
    
    .table-wrapper {
      flex: 1;
      overflow-y: auto;
    }
    
    .action-button {
      padding: 6px 0;
      color: #409EFF;
      
      &:hover {
        opacity: 0.8;
      }
      
      i {
        margin-right: 4px;
      }
    }
    
    .table-pagination {
      margin-top: 16px;
      display: flex;
      justify-content: center;
    }
  }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 4px;
}

::-webkit-scrollbar-track {
  background-color: #f5f7fa;
  border-radius: 4px;
}

.school-name-cell {
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  .el-input {
    width: 100%;
  }
}
</style>

<style lang="less">
.school-manage-header {
  .header-left {
    .el-select {
      width: 150px;
    }
  }
}

/* 美化表格样式 */
.school-manage {
  .el-table {
    /* 给表格边框添加圆角 */
    border-radius: 4px;
    overflow: hidden;
    
    /* 表头样式 */
    th.el-table__cell {
      font-size: 14px;
    }
    
    /* 表格行样式 */
    td.el-table__cell {
      padding: 12px 0;
    }
    
    /* 鼠标悬停行效果 */
    tr.el-table__row:hover > td.el-table__cell {
      background-color: #f0f7ff !important;
    }
    
    /* 选中的行样式 */
    tr.selected-school-row > td.el-table__cell {
      background-color: #e6f7f5 !important;
    }
    
    /* 斑马纹样式优化 */
    tr.el-table__row--striped > td.el-table__cell {
      background-color: #fafafa;
    }
  }
  
  /* 美化分页样式 */
  .el-pagination {
    button:not(:disabled) {
      &:hover {
        color: #40DBBC;
      }
    }
    
    .el-pager li:not(.disabled).active {
      background-color: #40DBBC;
      color: #fff;
    }
    
    .el-pager li:not(.disabled):hover {
      color: #40DBBC;
    }
  }
  
  /* 美化按钮样式 */
  .el-button--success {
    background-color: #50D166;
    border-color: #50D166;
    
    &:hover, &:focus {
      background-color: #67d97c;
      border-color: #67d97c;
    }
  }
  
  .el-button--primary {
    background-color: #409EFF;
    border-color: #409EFF;
    
    &:hover, &:focus {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
  }
}
</style>
